<?php

namespace app\controller;

use think\facade\Cookie;
use think\facade\Db;
use think\facade\View;
class Login
{
    public function index(){
        return View::fetch();
    }
    public function login()
    {
        //print_r(input("post."));
        $account = trim(input("post.username"));
        if (empty($account)) {
            echo json_encode(['code' => 1, 'msg' => '请输入账号']);
            exit;
        }
        $password = trim(input("post.password"));
        if (empty($password)) {
            echo json_encode(['code' => 1, 'msg' => '请输入密码']);
            exit;
        }
        $code = trim(input("post.code"));
        if (empty($code)) {
            echo json_encode(['code' => 1, 'msg' => '请输入验证码']);
            exit;
        }
        if (!captcha_check($code)) {//验证码检测 需要在middleware.php里打开session
            echo json_encode(['code' => 1, 'msg' => '验证码错误']);
            exit;
        }
        $user = Db::table('user')->where('username', $account)->find();
        if (empty($user)) {
            echo json_encode(['code' => 1, 'msg' => '没有找到账号']);
            exit;
        }
        if ($user['password'] != $password) {
            echo json_encode(['code' => 1, 'msg' => '密码错误']);
            exit;
        }
        Cookie::set('admin_id',$user['id']);
        Cookie::set('admin_account',$user['username']);
        $user_id = Cookie::get('admin_id');

        echo json_encode(['code' => 0, 'msg' => '登陆成功']);
    }
    public function logout(){
        Cookie::delete('admin_id');
        Cookie::delete('admin_account');
        echo json_encode(['code' => 0, 'msg' => '退出成功']);
    }
}